package lew.bing.gwalo.utils;

import lew.bing.gwalo.annotations.BingoCommand;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;

/**
 * Created by 刘国兵 on 2018/7/8.
 */
public class CommonUtils {

    public static String getKey(MethodSignature signature,String key, Object[] args) {
        String name = key;// key可以用annotation来弄
        if (StringUtils.isEmpty(name)) {
            name = signature.getName();
        } else {
            EvaluationContext context = new StandardEvaluationContext();
            String methodName = signature.getName();
            context.setVariable("methodName",methodName);
            String[] parameterNames = signature.getParameterNames();
            if (args != null) {
                if (parameterNames == null) {
                    parameterNames = new String[0];
                }
                for (int i = 0;i < args.length;i++) {
                    context.setVariable("arg"+i,args[i]);
                    if (parameterNames.length > i) {
                        context.setVariable(parameterNames[i],args[i]);
                    }
                }
            }
            ExpressionParser parser = new SpelExpressionParser();
            name = parser.parseExpression(name).getValue(context, String.class);
        }
        return name;
    }

}
